"""
用于爬取车站代号
"""
import requests
import re
import openpyxl


def get_station():
    url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9335'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0'
    }
    resp = requests.get(url, headers=headers)
    resp.encoding = 'utf-8'
    # print(resp.text)
    stations = re.findall(r'([\u4e00-\u9fa5]+)\|([A-Z]+)', resp.text)
    # print(stations)
    return stations # 返回一个元组列表


def save(lst0):
    wb = openpyxl.Workbook()    # 创建一个工作簿
    ws = wb.active  # 获取当前活动的工作表
    for row in lst0:
        ws.append(row)  # 将元组列表中的元组依次添加到工作表中
    wb.save('车站代码.xlsx')


if __name__ == '__main__':
    lst = get_station()
    save(lst)
